<template>
  <div class="login-container">
    <!-- 背景图案 -->
    <div class="bg-pattern"></div>
    <div class="bg-overlay"></div>
    
    <!-- 登录卡片 -->
    <div class="login-card">
      <!-- Logo区域 -->
      <div class="logo-area">
        <t-image
          class="logo-image"
          src="/static/title.jpg"
        ></t-image>
        <div class="app-title">一路相伴</div>
        <div class="app-slogan">专业陪玩服务平台</div>
      </div>
      
      <!-- 表单区域 -->
      <div class="form-area">
        <h2 class="form-title">欢迎登录</h2>
        
        <!-- 手机号输入 -->
        <div class="input-group">
          <t-input 
            class="custom-input" 
            placeholder="请输入手机号" 
            v-model="user.phone" 
            @change="checkphone"
            size="large"
            :maxlength="11"
          >
            <template #prefixIcon>
              <phone-icon />
            </template>
          </t-input>
          <div class="input-bar"></div>
        </div>
        
        <!-- 密码输入 -->
        <div class="input-group">
          <t-input 
            class="custom-input" 
            placeholder="请输入密码" 
            v-model="user.pass" 
            :type="passwordVisible ? 'text' : 'password'"
            size="large"
          >
            <template #prefixIcon>
              <Password-icon />
            </template>
            <template #suffixIcon>
              <div @click="togglePasswordVisibility">
                <BrowseOffIcon v-if="!passwordVisible" />
                <BrowseIcon v-else />
              </div>
            </template>
          </t-input>
          <div class="input-bar"></div>
        </div>
        <!-- 验证码 -->
        <div class="input-group code-group">
          <div class="code-input-wrapper">
            <t-input 
              class="custom-input code-input" 
              placeholder="请输入验证码" 
              v-model="user.code" 
              size="large"
              :maxlength="6"
            >
              <template #prefixIcon>
                <code-icon />
              </template>
            </t-input>
            <t-button 
              class="get-code-btn" 
              @click="getCode" 
              size="large"
              :disabled="countdown > 0"
              :loading="codeLoading"
            >
              {{ countdown > 0 ? `${countdown}s后重试` : '获取验证码' }}
            </t-button>
          </div>
          <div class="input-bar"></div>
        </div>

        
        <!-- 登录按钮 -->
        <t-button 
          class="login-btn" 
          shape="round" 
          block 
          @click="login"
          :loading="isLoading"
        >
          登录
        </t-button>
        
        <!-- 其他选项 -->
        <div class="options-area">
          <span class="option-link" @click="tz('/find')">忘记密码</span>
          <span class="option-link" @click="tz('/register')">注册新账号</span>
        </div>
      </div>
      
      <!-- 社交登录 -->
      <div class="social-login">
        <div class="divider-text">其他登录方式</div>
        <div class="social-icons">
          <div class="social-icon wechat">
            <icon-font name="logo-wechat" /><span style="font-size: 15px;">微信</span>
          </div>
          <div class="social-icon qq">
            <icon-font name="logo-qq" /><span style="font-size: 15px;">QQ</span>
          </div>
        </div>
      </div>
      
      <!-- 协议区域 -->
      <div class="agreement-area">
        <t-checkbox v-model="agreedToTerms">
          <span class="agreement-text">
            我已阅读并同意 
            <span class="agreement-link" @click.stop="showTerms('用户协议')">《用户协议》</span>
            和
            <span class="agreement-link" @click.stop="showTerms('服务协议')">《服务协议》</span>
          </span>
        </t-checkbox>
      </div>
    </div>
  </div>
</template>

<script setup lang="ts">
import { useRouter } from "vue-router";
import { ref } from "vue";
import { get, post } from "../util/Request";
import { Toast } from 'tdesign-mobile-vue';
import { BrowseIcon } from 'tdesign-icons-vue-next';
import axios from "axios";

// 变量定义
const user = ref({
  phone: '',
  pass: '',
  code: ''
});
const router = useRouter();
const passwordVisible = ref(false);
const agreedToTerms = ref(false);
const isLoading = ref(false);
const countdown = ref(0);
const codeLoading = ref(false);

// 页面跳转
const tz = (url) => {
  router.push(url);
};

// 切换密码可见性
const togglePasswordVisibility = () => {
  passwordVisible.value = !passwordVisible.value;
};

// 展示协议内容
const showTerms = (type) => {
  Toast({
    message: `${type}内容正在准备中...`,
    theme: 'info',
    duration: 2000
  });
};

// 校验手机号
const checkphone = () => {
  if (user.value.phone.length === 11) {
    // 检查手机号是否可用
    get("user/checkphone?phone=" + user.value.phone).then(res => {
      if (res.data.code == 200) {
        // 手机号不存在
        Toast({
          duration: 3000,
          theme: 'error',
          message: '该手机号尚未注册，请先完成注册'
        });
      }
    }).catch(err => {
      Toast({
        duration: 2000,
        theme: 'error',
        message: '网络请求失败，请检查网络连接'
      });
    });
  }
};


// 修改后的获取验证码方法
const getCode = () => {
  if (countdown.value > 0) return;
  
  // 验证手机号格式
  if (!/^1[3-9]\d{9}$/.test(user.value.phone)) {
    showCustomToast('请输入正确的手机号', 'warning');
    return;
  }

  codeLoading.value = true;
  
  get(`user/code?phone=${user.value.phone}`).then(res => {
    if (res.data.code === 200) {
      showCustomToast('验证码已发送', 'success');
      // 开始150秒倒计时
      startCountdown(150);
    } else {
      showCustomToast(res.data.msg || '发送验证码失败', 'error');
    }
  }).catch(() => {
    showCustomToast('网络请求失败', 'error');
  }).finally(() => {
    codeLoading.value = false;
  });
};

// 倒计时方法
const startCountdown = (seconds: number) => {
  countdown.value = seconds;
  const timer = setInterval(() => {
    countdown.value--;
    if (countdown.value <= 0) {
      clearInterval(timer);
    }
  }, 1000);
};

// 自定义Toast样式
const showCustomToast = (message: string, type: 'success' | 'error' | 'warning') => {
  const bgColor = {
    success: '#67c23a',
    error: '#f56c6c',
    warning: '#e6a23c'
  }[type];
  
  Toast({
    message,
    duration: 2000,
    style: {
      background: bgColor,
      color: '#fff',
      borderRadius: '8px',
      padding: '12px 20px',
      boxShadow: '0 4px 12px rgba(0, 0, 0, 0.15)'
    }
  });
};

// 登录账号
const login = () => {
  // 表单验证
  if (!user.value.phone) {
    Toast({ message: '请输入手机号', theme: 'warning' });
    return;
  }
  
  if (!user.value.pass) {
    Toast({ message: '请输入密码', theme: 'warning' });
    return;
  }
  if(!user.value.code) {
    Toast({ message: '请输入验证码', theme: 'warning' });
    return;
  }
  
  if (!agreedToTerms.value) {
    Toast({ message: '请阅读并同意协议', theme: 'warning' });
    return;
  }
  
  // 开始登录
  isLoading.value = true;
  
  // 请求接口实现用户登录
  post("user/login", user.value).then(res => {
    isLoading.value = false;
    
    if (res.data.code == 200) {
      Toast({
        message: "登录成功!",
        theme: 'success',
        duration: 2000,
      });
      
      // 存储信息
      sessionStorage.setItem("token", res.data.data.token);
      sessionStorage.setItem("user", JSON.stringify(res.data.data.user));
      sessionStorage.setItem("detail", JSON.stringify(res.data.data.detail));
      sessionStorage.setItem("uid", res.data.data.user.id);
      
      // 跳转到首页
      setTimeout(() => {
        router.push("/");
      }, 1000);
    } else {
      Toast({
        message: "密码/验证码错误!",
        theme: 'error',
        duration: 3000
      });
    }
  }).catch(() => {
    isLoading.value = false;
    Toast({
      message: "登录失败，请检查网络连接",
      theme: 'error',
      duration: 3000
    });
  });
};
</script>

<style scoped>
.login-container {
  min-height: 100vh;
  display: flex;
  justify-content: center;
  align-items: center;
  position: relative;
  overflow: hidden;
  padding: 20px;
  background-color: #f5f7fa;
}

/* 背景样式 */
.bg-pattern {
  position: absolute;
  top: 0;
  left: 0;
  width: 100%;
  height: 100%;
  background-image: linear-gradient(135deg, #f5f7fa 25%, transparent 25%),
                    linear-gradient(225deg, #f5f7fa 25%, transparent 25%),
                    linear-gradient(45deg, #f5f7fa 25%, transparent 25%),
                    linear-gradient(315deg, #f5f7fa 25%, #e4e8f0 25%);
  background-position: 25px 0, 25px 0, 0 0, 0 0;
  background-size: 50px 50px;
  background-repeat: repeat;
  opacity: 0.3;
  z-index: 0;
}

.bg-overlay {
  position: absolute;
  top: 0;
  left: 0;
  width: 100%;
  height: 100%;
  background: linear-gradient(120deg, rgba(66, 103, 212, 0.5), rgba(219, 77, 109, 0.4));
  z-index: 0;
}

/* 登录卡片样式 */
.login-card {
  width: 100%;
  max-width: 400px;
  background-color: white;
  border-radius: 16px;
  box-shadow: 0 10px 30px rgba(0, 0, 0, 0.1);
  padding: 30px;
  position: relative;
  z-index: 1;
  animation: fadeInUp 0.8s ease-out;
}

@keyframes fadeInUp {
  from {
    transform: translateY(30px);
    opacity: 0;
  }
  to {
    transform: translateY(0);
    opacity: 1;
  }
}

/* Logo区域样式 */
.logo-area {
  display: flex;
  flex-direction: column;
  align-items: center;
  margin-bottom: 30px;
}

.logo-image {
  width: 80px;
  height: 80px;
  border-radius: 16px;
  object-fit: cover;
  margin-bottom: 16px;
  box-shadow: 0 4px 10px rgba(0, 0, 0, 0.08);
}

.app-title {
  font-size: 24px;
  font-weight: 600;
  color: #333;
  margin-bottom: 6px;
  letter-spacing: 1px;
}

.app-slogan {
  font-size: 14px;
  color: #888;
  text-align: center;
}

/* 表单区域样式 */
.form-area {
  margin-bottom: 20px;
}

.form-title {
  font-size: 20px;
  font-weight: 600;
  color: #333;
  margin-bottom: 25px;
  text-align: center;
}

.input-group {
  margin-bottom: 25px;
  position: relative;
}

.custom-input {
  background-color: #f8f9fb;
  border-radius: 18px;
  border: 1px solid transparent;
  transition: all 0.3s ease;
}

.custom-input:hover, .custom-input:focus {
  border-color: #d84c75;
  background-color: white;
}

.input-bar {
  position: absolute;
  bottom: 0;
  left: 50%;
  width: 0;
  height: 2px;
  background: linear-gradient(to right, #4267d4, #d84c75);
  transition: all 0.3s ease;
  transform: translateX(-50%);
}

.custom-input:focus ~ .input-bar {
  width: 100%;
}

/* 登录按钮样式 */
.login-btn {
  height: 50px;
  margin-top: 10px;
  margin-bottom: 15px;
  background: linear-gradient(45deg, #4267d4, #d84c75);
  color: white;
  font-size: 16px;
  font-weight: 500;
  border: none;
  box-shadow: 0 4px 15px rgba(216, 76, 117, 0.3);
  transition: all 0.3s ease;
  border-radius: 30px;
}

.login-btn:hover, .login-btn:active {
  transform: translateY(-2px);
  box-shadow: 0 6px 20px rgba(216, 76, 117, 0.4);
}

/* 选项区域样式 */
.options-area {
  display: flex;
  justify-content: space-between;
  margin-bottom: 20px;
}

.option-link {
  color: #4267d4;
  font-size: 14px;
  cursor: pointer;
  transition: color 0.3s ease;
}

.option-link:hover {
  color: #d84c75;
  text-decoration: underline;
}

/* 社交登录样式 */
.social-login {
  margin-bottom: 20px;
}

.divider-text {
  text-align: center;
  position: relative;
  margin-bottom: 20px;
  color: #aaa;
  font-size: 14px;
}

.divider-text::before,
.divider-text::after {
  content: '';
  position: absolute;
  top: 50%;
  width: 25%;
  height: 1px;
  background-color: #eee;
}

.divider-text::before {
  left: 10%;
}

.divider-text::after {
  right: 10%;
}

.social-icons {
  display: flex;
  justify-content: center;
  gap: 20px;
}

.social-icon {
  width: 44px;
  height: 44px;
  border-radius: 50%;
  display: flex;
  justify-content: center;
  align-items: center;
  color: white;
  font-size: 22px;
  cursor: pointer;
  transition: transform 0.3s ease, box-shadow 0.3s ease;
}

.social-icon:hover {
  transform: translateY(-3px);
}

.wechat {
  background-color: #09bb07;
  box-shadow: 0 3px 8px rgba(9, 187, 7, 0.3);
}

.wechat:hover {
  box-shadow: 0 5px 12px rgba(9, 187, 7, 0.4);
}

.qq {
  background-color: #12b7f5;
  box-shadow: 0 3px 8px rgba(18, 183, 245, 0.3);
}

.qq:hover {
  box-shadow: 0 5px 12px rgba(18, 183, 245, 0.4);
}

.weibo {
  background-color: #e6162d;
  box-shadow: 0 3px 8px rgba(230, 22, 45, 0.3);
}

.weibo:hover {
  box-shadow: 0 5px 12px rgba(230, 22, 45, 0.4);
}

/* 协议区域样式 */
.agreement-area {
  text-align: center;
}

.agreement-text {
  font-size: 12px;
  color: #888;
}

.agreement-link {
  color: #4267d4;
  cursor: pointer;
  transition: color 0.3s ease;
}

.agreement-link:hover {
  color: #d84c75;
  text-decoration: underline;
}

/* 响应式调整 */
@media screen and (max-width: 480px) {
  .login-card {
    padding: 20px;
    max-width: 340px;
  }
  
  .logo-image {
    width: 70px;
    height: 70px;
  }
  
  .app-title {
    font-size: 22px;
  }
  
  .form-title {
    font-size: 18px;
  }
}
/* 新增的样式 */
.code-group {
  position: relative;
}

.code-input-wrapper {
  display: flex;
  gap: 10px;
}

.code-input {
  flex: 1;
}

.get-code-btn {
  width: 100px;
  height: 57.34px;
  flex-shrink: 0;
  background: linear-gradient(45deg, #67d46e, #4cd84c);
  color: white;
  border: none;
  transition: all 0.3s;
  border-radius: 10px;
}

.get-code-btn:hover {
  opacity: 0.9;
  transform: translateY(-1px);
}

.get-code-btn:disabled {
  background: #cccccc;
  transform: none;
  cursor: not-allowed;
}
</style>